package de.preiscrawler.parser.media_deal;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

import de.preiscrawler.AlleAnbieter;
import de.preiscrawler.parser.AbstractParser;
import de.preisrobot.entity.AbstractEntity;
import de.preisrobot.entity.Artikel;
import de.preisrobot.service.internal.PreisRobotParserException;

public class MediaDealParser  extends AbstractParser<Artikel> {

	@Override
	public int getAnbieter() {

		return AlleAnbieter.MEDIA_DEAL;
	}

	@Override
	protected void parseStream(List<Artikel> list, InputStream in)
			throws IOException, PreisRobotParserException {

		final Source source = new Source(in);
		final List<Element> li_productData = source
				.getAllElementsByClass("productData ");

		for (Element productData : li_productData) {

			List<Element> infoBox = productData
					.getAllElementsByClass("infoBox");
			Element element = infoBox.get(0);

			List<Element> allElementsByClass2 = element
					.getAllElementsByClass("title");
			String title = extractTextFromSingleElement(allElementsByClass2);
			String fullURL = allElementsByClass2.get(0).getAttributeValue(
					"href");
			String mediatyp = extractTextFromSingleElement(element
					.getAllElementsByClass("mediatyp"));
			String rlsdate = extractTextFromSingleElement(element
					.getAllElementsByClass("rlsdate"));

			String longdesc = extractTextFromSingleElement(element
					.getAllElementsByClass("longdesc"));
			String runtime = extractTextFromSingleElement(element
					.getAllElementsByClass("runtime"));

			List<Element> pictureBox = productData
					.getAllElementsByClass("pictureBox");
			String imgUrl = pictureBox.get(0).getAllElements("img").get(0)
					.getAttributeValue("src");

			String price = extractTextFromSingleElement(source
					.getAllElementsByClass("price"));

			Artikel a = new Artikel();
			a.setAnbieterId(this.getAnbieter());
			a.setArtikelLink(fullURL);
			a.setArtikelPreislink(rlsdate);
			a.setDesc(longdesc);
			a.setImageLink(imgUrl);
			a.setPreis(price);
			a.setArtikelPreislink(title);

			list.add(a);

		}

	}

	/*
	 * extract the content of a element foud by class we know that the list
	 * would only contain one element from which we need the text
	 * 
	 * @param title
	 * 
	 * @return
	 */
	private String extractTextFromSingleElement(List<Element> title) {
		if (title == null || title.size() < 1) {
			return "";
		}

		Element element = title.get(0);
		return element.getTextExtractor().toString();

	}

}
